import java.util.Random;

public class Board {
    private int[][] activeBoard, inactiveBoard;

    public int height = 500, width = 500;

    Board() {
        randomInit();
    }

    Board(int height, int width) {
        this.height = height;
        this.width = width;
        randomInit();
    }

    public int[][] getActiveBoard() {
        return activeBoard;
    }

    public void randomInit() {
        activeBoard = new int[height+2][width+2];
        inactiveBoard = new int[height+2][width+2];

        // 使用boardA进行初始随机赋值
        Random random = new Random();
        for (int i = 1; i < height+1; i++) {
            for (int j = 1; j < width+1; j++) {
                activeBoard[i][j] = random.nextInt(2);
            }
        }
    }

    public void showBoard() {
        for (int i = 0; i < height+2; i++) {
            for (int j = 0; j < width+2; j++) {
                if (activeBoard[i][j] == 0) {
                    System.out.print("O " );
                } else if (activeBoard[i][j] == 1) {
                    System.out.print("* " );
                } else {
                    System.out.print("? " );
                }

            }
            System.out.println();
        }
    }

    public void nextState() {
        for (int i = 1; i < height + 1; i++) {
            for (int j = 1; j < width + 1; j++) {
                changePoint(i, j);
            }
        }
        switchActiveBoard();
    }


    private void changePoint(int row, int col) {
        int sum = 0;
        for (int i = row - 1; i <= row + 1; i++) {
            for (int j = col - 1; j <= col + 1; j++) {
                sum += activeBoard[i][j];
            }
        }
        sum -= activeBoard[row][col];
        if (activeBoard[row][col] == 0) {
            // unpopulated
            if (sum == 3) {
                // get populated
                inactiveBoard[row][col] = 1;
            } else {
                inactiveBoard[row][col] = 0;
            }
        } else {
            // populated
            if (sum < 2 || sum > 3) {
                inactiveBoard[row][col] = 0;
            } else {
                // survive
                inactiveBoard[row][col] = 1;
            }
        }
    }

    private void switchActiveBoard() {
        int[][] tmp = activeBoard;
        activeBoard = inactiveBoard;
        inactiveBoard = tmp;
    }

}
